package router

import (
	"context"
	"github.com/aberic/gnomon/grope"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"net/http"
	"time"
)

func RouteContainer(hs *grope.GHttpServe) {
	// 仓库相关路由设置
	route := hs.Group("/container")
	route.Get("/logs/:id/:since/:until", containerLogs) // 20200518032852 20200518033200
	route.Get("/list", containerList)
	route.Get("/inspect/:id", containerInspect)
}

func containerLogs(ctx *grope.Context) {
	var (
		since, until time.Time
		bs           []byte
		err          error
	)
	since, err = time.Parse("20060102150405", ctx.Value("since"))
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	until, err = time.Parse("20060102150405", ctx.Value("until"))
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	bs, _ = client.Obtain().Container().Logs(context.Background(), ctx.Value("id"), since, until)
	_ = ctx.ResponseText(http.StatusOK, string(bs))
}

func containerList(ctx *grope.Context) {
	containers, err := client.Obtain().Container().List(context.Background())
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: containers})
}

func containerInspect(ctx *grope.Context) {
	container, _, err := client.Obtain().Container().Inspect(context.Background(), ctx.Value("id"))
	if nil != err {
		responseFailJSON(ctx, err)
		return
	}
	_ = ctx.ResponseJSON(http.StatusOK, &response{Code: CodeSuccess, Data: container})
}
